/*
 * Copyright (C) 2021 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package me.minetsh.imaging.photoview.ui;

import me.minetsh.imaging.ResourceTable;
import me.minetsh.imaging.crop.CropImageView;
import me.minetsh.imaging.crop.callback.CropCallback;
import me.minetsh.imaging.crop.callback.LoadCallback;
import me.minetsh.imaging.imageData.ImagePicker;
import me.minetsh.imaging.view.GlobalData;
import ohos.aafwk.ability.Ability;
import ohos.aafwk.content.Intent;
import ohos.agp.components.Component;
import ohos.agp.utils.Color;
import ohos.agp.utils.RectFloat;
import ohos.bundle.IBundleManager;
import ohos.media.image.PixelMap;
import ohos.utils.net.Uri;

public class ImageCropAbility extends Ability {
    private static final String KEY_FRAME_RECT_LEFT = "FrameRectLeft";
    private static final String KEY_FRAME_RECT_TOP = "FrameRectTop";
    private static final String KEY_FRAME_RECT_RIGHT = "FrameRectRight";
    private static final String KEY_FRAME_RECT_BOTTOM = "FrameRectBottom";
    private static final String KEY_SOURCE_URI = "SourceUri";

    // Views ///////////////////////////////////////////////////////////////////////////////////////
    private CropImageView mCropView;
    private String format = "jpeg";
    private RectFloat mFrameRect = null;
    private Uri mSourceUri = null;

    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
        super.setUIContent(ResourceTable.Layout_ability_basic);
        int color = Color.getIntColor("#000000");
        getWindow().setStatusBarColor(color);

        mCropView = (CropImageView) findComponentById(ResourceTable.Id_cropImageView);
        mCropView.setCropMode(CropImageView.CropMode.FIT_IMAGE);
        bindViews();
        if (intent.getFloatParam(KEY_FRAME_RECT_LEFT, 0) != 0) {
            mFrameRect = new RectFloat(intent.getFloatParam(KEY_FRAME_RECT_LEFT, 0),
                    intent.getFloatParam(KEY_FRAME_RECT_TOP, 0),
                    intent.getFloatParam(KEY_FRAME_RECT_RIGHT, 0),
                    intent.getFloatParam(KEY_FRAME_RECT_BOTTOM, 0));
            mSourceUri = intent.getSequenceableParam(KEY_SOURCE_URI);
        }
        if (mSourceUri == null) {
            mSourceUri = intent.getSequenceableParam("uri");
        }
        PixelMap pixelMap = GlobalData.getInstance().getCropperPixelMap();
        mSourceUri = mCropView.saveImage(System.currentTimeMillis() + "", pixelMap);
        mCropView.load(mSourceUri)
                .initialFrameRect(mFrameRect)
                .useThumbnail(true)
                .execute(mLoadCallback);
    }

    @Override
    protected void onForeground(Intent intent) {
        super.onForeground(intent);
        intent.setParam(KEY_FRAME_RECT_LEFT, mCropView.getActualCropRect().left);
        intent.setParam(KEY_FRAME_RECT_TOP, mCropView.getActualCropRect().top);
        intent.setParam(KEY_FRAME_RECT_RIGHT, mCropView.getActualCropRect().right);
        intent.setParam(KEY_FRAME_RECT_BOTTOM, mCropView.getActualCropRect().bottom);
        intent.setParam(KEY_SOURCE_URI, mCropView.getSourceUri());
    }

    private void bindViews() {
        mCropView = (CropImageView) findComponentById(ResourceTable.Id_cropImageView);
        findComponentById(ResourceTable.Id_buttonDone).setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {
                if (verifySelfPermission("ohos.permission.WRITE_USER_STORAGE") != IBundleManager.PERMISSION_GRANTED) {
                    if (canRequestPermission("ohos.permission.WRITE_USER_STORAGE")) {
                        requestPermissionsFromUser(
                                new String[]{"ohos.permission.WRITE_USER_STORAGE"}, 100);
                    } else {
                    }
                } else {
                    mCropView.crop(mSourceUri).execute(mCropCallback);
                }
            }
        });
        findComponentById(ResourceTable.Id_buttonRotateLeft).setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {
                mCropView.rotateImage(CropImageView.RotateDegrees.ROTATE_M90D);
            }
        });
        findComponentById(ResourceTable.Id_buttonCancel).setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {
                terminateAbility();
            }
        });
        findComponentById(ResourceTable.Id_buttonReset).setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {
                mCropView.resetCrop();
            }
        });
    }

    private final LoadCallback mLoadCallback = new LoadCallback() {
        @Override
        public void onSuccess() {
        }

        @Override
        public void onError(Throwable e) {
        }
    };


    @Override
    public void onRequestPermissionsFromUserResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsFromUserResult(requestCode, permissions, grantResults);
        if (requestCode == 100) {
            mCropView.crop(mSourceUri).execute(mCropCallback);
        }
    }

    @Override
    protected void onAbilityResult(int requestCode, int resultCode, Intent resultData) {
        super.onAbilityResult(requestCode, resultCode, resultData);
        if (requestCode == 1 && resultCode == 1) {
            mSourceUri = resultData.getSequenceableParam("uri");
            mCropView.load(mSourceUri)
                    .initialFrameRect(mFrameRect)
                    .useThumbnail(true)
                    .execute(mLoadCallback);
        }
    }

    private final CropCallback mCropCallback = new CropCallback() {
        @Override
        public void onSuccess(PixelMap cropped) {
            startResultActivity(cropped);
        }

        @Override
        public void onError(Throwable e) {
        }
    };


    /**
     * startResultActivity
     *
     * @param uri uri
     */
    public void startResultActivity(PixelMap uri) {
        if (isTerminating()) {
            return;
        }

        Intent intent = new Intent();
        intent.setParam("resultUri", "");
        GlobalData.getInstance().setCropperPixelMap(uri);
        setResult(ImagePicker.REQUEST_CODE_CROP, intent); // 多选不允许裁剪裁剪，返回数据
        terminateAbility();
    }

    @Override
    protected void onStop() {
        super.onStop();
        if (mSourceUri != null) {
            mCropView.deleteImage(mSourceUri);
        }
    }
}
